package com.edu.whty.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edu.whty.common.tools.HttpClient;
import com.edu.whty.common.tools.OpenUtil;
import com.edu.whty.common.tools.kafka.CommonMessage;
import com.edu.whty.entity.cloud.TbCourseRes;
import com.edu.whty.entity.cloud.TbCourseUser;
import com.edu.whty.entity.usertextbook.TbUserTextbookChapter;
import com.edu.whty.entity.usertextbook.UserTextBook;
import com.edu.whty.service.CourseService;
import com.edu.whty.service.SystemService;
import com.edu.whty.service.UserTextBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SystemServiceImpl implements SystemService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${rrtbk.url}")
    private String rrtbkUrl;

    @Value("${rrtbk.api.listUserTextBook}")
    private String listUserTextBook;

    @Value("${rrtbk.api.queryChapters}")
    private String queryChapters;

    @Value("${rrtbk.api.initCourseResList}")
    private String initCourseResList;

    @Value("${rrtbk.api.initCourseUserList}")
    private String initCourseUserList;

    @Autowired
    private UserTextBookService userTextBookService;

    @Autowired
    private CourseService courseService;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @Override
    public boolean init(String orgId) {
        try {
            //初始化教材表
            String textbookUrl = rrtbkUrl + listUserTextBook+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
            JSONObject textbookParam = new JSONObject();
            textbookParam.put("orgId", orgId);
            textbookParam.put("status", "-1");
            logger.info("初始化教材url:" + textbookUrl + ";请求参数:" + textbookParam.toJSONString());
            String textbookResponse = HttpClient.doJSONPostMethod(textbookUrl, textbookParam.toJSONString());
            JSONObject textbookResponseObject = JSONObject.parseObject(textbookResponse);
            if(!textbookResponseObject.getString("resCode").equals("000000")){
                return false;
            } else {
                JSONArray array = textbookResponseObject.getJSONArray("data");
                List<UserTextBook> userTextBookList = new ArrayList<UserTextBook>();
                for(Object o : array) {
                    String jsonString = JSONObject.toJSONString(o);
                    UserTextBook userTextBook = JSONObject.parseObject(jsonString, UserTextBook.class);
                    userTextBookList.add(userTextBook);
                }

                userTextBookService.saveTextBookBatch(userTextBookList);
            }

            //初始化教材表章节
            String textbookChapterUrl = rrtbkUrl + queryChapters+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
            JSONObject textbookChapterParam = new JSONObject();
            textbookChapterParam.put("orgId", orgId);
            textbookChapterParam.put("status", "-1");
            logger.info("初始化教材章节url:" + textbookChapterUrl + ";请求参数:" + textbookChapterParam.toJSONString());
            String textbookChapterResponse = HttpClient.doJSONPostMethod(textbookChapterUrl, textbookChapterParam.toJSONString());
            JSONObject textbookChapterResponseObject = JSONObject.parseObject(textbookChapterResponse);
            if(!textbookChapterResponseObject.getString("resCode").equals("000000")){
                return false;
            } else {
                JSONArray array = textbookChapterResponseObject.getJSONArray("data");
                List<TbUserTextbookChapter> userTextbookChapterList = new ArrayList<TbUserTextbookChapter>();
                for(Object o : array) {
                    String jsonString = JSONObject.toJSONString(o);
                    TbUserTextbookChapter userTextbookChapter = JSONObject.parseObject(jsonString, TbUserTextbookChapter.class);
                    userTextbookChapterList.add(userTextbookChapter);
                }

                userTextBookService.saveTextBookChapterBatch(userTextbookChapterList);
            }

            //初始化备课
            String courseResUrl = rrtbkUrl + initCourseResList+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
            JSONObject courseResParam = new JSONObject();
            courseResParam.put("orgId", orgId);
            logger.info("初始化courseRes url:" + courseResUrl + ";请求参数:" + courseResParam.toJSONString());
            String courseResResponse = HttpClient.doJSONPostMethod(courseResUrl, courseResParam.toJSONString());
            JSONObject courseResResponseObject = JSONObject.parseObject(courseResResponse);
            if(!courseResResponseObject.getString("resCode").equals("000000")){
                return false;
            } else {
                JSONArray array = courseResResponseObject.getJSONArray("data");
                List<TbCourseRes> courseResList = new ArrayList<TbCourseRes>();
                for(Object o : array) {
                    String jsonString = JSONObject.toJSONString(o);
                    TbCourseRes courseRes = JSONObject.parseObject(jsonString, TbCourseRes.class);
                    courseResList.add(courseRes);
                }

                courseService.saveCourseResBatch(courseResList);
            }

            String courseUserUrl = rrtbkUrl + initCourseUserList+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
            JSONObject courseUserParam = new JSONObject();
            courseUserParam.put("orgId", orgId);
            logger.info("初始化courseUser url:" + courseUserUrl + ";请求参数:" + courseUserParam.toJSONString());
            String courseUserResponse = HttpClient.doJSONPostMethod(courseUserUrl, courseUserParam.toJSONString());
            JSONObject courseUserResponseObject = JSONObject.parseObject(courseUserResponse);
            if(!courseUserResponseObject.getString("resCode").equals("000000")){
                return false;
            } else {
                JSONArray array = courseUserResponseObject.getJSONArray("data");
                List<TbCourseUser> courseUserList = new ArrayList<TbCourseUser>();
                for(Object o : array) {
                    String jsonString = JSONObject.toJSONString(o);
                    TbCourseUser courseUser = JSONObject.parseObject(jsonString, TbCourseUser.class);
                    courseUserList.add(courseUser);
                }

                courseService.saveCourseUserBatch(courseUserList);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("初始化失败：" + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean upSync(CommonMessage commonMessage) {
        try {
            if(isCloud) {
                if("tb_user_textbook".equals(commonMessage.getTable())) {
                    userTextBookService.syncSaveOrUpdateBatch(commonMessage.getData());
                } else if("tb_course_res".equals(commonMessage.getTable())) {
                    courseService.syncSaveOrUpdateCourseResBatch(commonMessage.getData());
                } else if("tb_course_user".equals(commonMessage.getTable())) {
                    courseService.syncSaveOrUpdateCourseUserBatch(commonMessage.getData());
                }
            }

            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

}
